﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebFormBlog
{
    public partial class Archive : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string str_year = Convert.ToInt32(Request.QueryString["year"]).ToString();
            PageTitleLiteral.Text = str_year;
            YearLiteral.Text = str_year;
            int year = Convert.ToInt32(str_year);
            /* Dataset Query
            BlogDataSetTableAdapters.postTableAdapter pta = new BlogDataSetTableAdapters.postTableAdapter();
            PostListRepeater.DataSource = pta.GetDataByYear(str_year);
            PostListRepeater.DataBind();
            */

            BlogModel.BlogEntities db = new BlogModel.BlogEntities();
            var posts = from post in db.posts
                        where post.created_at.Year == year
                        orderby post.id descending
                        select post;
            PostListRepeater.DataSource = posts;
            PostListRepeater.DataBind();

            var prev_year = (from post in db.posts
                               where post.created_at.Year < year
                               orderby post.id descending
                               select post.created_at.Year).FirstOrDefault();
            var next_year = (from post in db.posts
                             where post.created_at.Year > year
                             orderby post.id ascending
                             select post.created_at.Year).FirstOrDefault();
            if (prev_year > 0)
            {
                prev.Attributes["href"] = "Archive.aspx?year=" + prev_year;
                prev.Title = prev_year.ToString();
            }
            else
            {
                prev.Visible = false;
            }
            if (next_year > 0)
            {
                next.Attributes["href"] = "Archive.aspx?year=" + next_year;
                next.Title = next_year.ToString();
            }
            else
            {
                next.Visible = false;
            }
        }
    }
}